package com.app.service.impl;

import com.app.domain.bo.SettingBo;
import com.app.domain.po.SettingPo;
import com.app.domain.vo.SettingVo;
import com.app.framework.utils.CoBeanUtils;
import com.app.mapper.SettingMapper;
import com.app.service.SettingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统设置方法实现
 */
@Service
public class SettingServiceImpl extends ServiceImpl<SettingMapper, SettingPo> implements SettingService {

    /**
     * 系统设置详情
     */
    @Override
    @Cacheable(cacheNames = "setting")
    public Map<String, Object> details() {
        List<SettingVo> settingVos = baseMapper.details();
        Map<String, Object> settingMap = new HashMap<>();
        for (SettingVo settingVo : settingVos) {
            settingMap.put(settingVo.getCode(), settingVo.getContent());
        }
        return settingMap;
    }

    /**
     * 修改系统设置
     *
     * @param bo 入参
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = {"setting", "setting_favorites", "favorites_articles"}, allEntries = true)
    public void updateOne(SettingBo bo) {
        SettingVo settingVo = baseMapper.selectSettingByCode(bo.getCode());
        Assert.notNull(settingVo, "该配置不存在");
        SettingPo settingPo = CoBeanUtils.copy(settingVo, SettingPo.class);
        settingPo.setContent(bo.getContent());
        baseMapper.updateById(settingPo);
    }

}